<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\admin\model\carousel\Images;
use app\admin\model\Announcements;
use app\admin\model\Goods;
use app\common\model\Category;
use app\admin\model\giy\Evaluate;
use app\admin\model\giy\Order as Orders;
use think\Exception;

/**
 * 首页接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 创建订单
     *
     */
    public function createOrder()
    {
        $user = $this->auth->getUserinfo();
        $goods_id = $this->request->param('goods_id');
        $quantity = $this->request->param('quantity');
        $total_amount = $this->request->param('total_amount');
        $address_id = $this->request->param('address_id');
        $pay_type = $this->request->param('pay_type');
        $goods_type = $this->request->param('goods_type');
        $memo = $this->request->param('memo');
        if (!$goods_id || !$quantity || !$total_amount || !$address_id || !$address_id || !$pay_type || !$goods_type) {
            $this->error(__('Invalid parameters'));
        }
        $goods_info= Db::name('goods')->where('goods_id',$goods_id)->find();
        if($goods_info['stock']<1){
            $this->error(__('Insufficient stock'));
        }
        $data = array(
            'order_sn' => $this->generateUniqueOrderNumber(15),
            'user_id' => $user['id'],
            'goods_id' => $goods_id,
            'quantity' => $quantity,
            'total_amount' => $total_amount,
            'address_id' => $address_id,
            'pay_type' => $pay_type,
            'goods_type' => $goods_type,
            'memo' => $memo,
            'createtime' => time()
        );
        Db::startTrans();
        try {
            $order_id = Db::name('order')->insertGetId($data);
            if ($order_id) {
                Db::name('goods')->where('goods_id',$goods_id)->setDec('stock',1);
                Db::name('goods')->where('goods_id',$goods_id)->setInc('sales',1);
            } else {
                throw new Exception("Operation failed");
            }
            Db::commit();
            $this->success(__('Operation completed'), $order_id);
        }catch (Exception $e){
          Db::rollback();
          $this->error($e->getMessage());
        }

    }

    function generateUniqueOrderNumber($length = 15)
    {
        // 时间戳
        $timestamp = time();

        // 随机数
        $randomNumber = mt_rand(100000, 999999);

        // 拼接字符串
        $uniqueNumber = 'sn' . $timestamp . $randomNumber;

        // 根据需要长度截取
        return substr($uniqueNumber, 0, $length);
    }

    //订单详情
    public function orderDetails()
    {
        $user = $this->auth->getUserinfo();
        $order_id = $this->request->param('order_id');
        $info = Db::name('order')->alias('o')
            ->join('goods g', 'o.goods_id = g.goods_id')
            ->join('user_address a', 'o.address_id = a.address_id')
            ->where('o.order_id', $order_id)
            ->field('o.*,g.name,g.price,g.stock,g.sales,g.goods_image,g.description,a.recipient_name,a.phone_number,a.address_line,a.area,a.city,a.province')
            ->paginate()->each(function ($item) {
                $item['goods_image'] = cdnurl($item['goods_image'], true);
                $item['createtime'] = date("Y-m-d H:i:s", $item['createtime']);
                $item['updatetime'] = date("Y-m-d H:i:s", $item['updatetime']);
                $item['express_info']=[];
                if($item['order_status']==5 && $item['expresssn'] ){
                    $item['express_info']=  $this->getExpress($item['expressquery_id'],$item['expresssn'],$item['phone_number']);
                }
                return $item;
            });

        $this->success(__('Operation completed'), $info);
    }
    public function getExpress($expressquery_id,$expresssn,$phone){
        $expModle = new \addons\expressquery\library\Expressquery();
        $expressquery_info=Db::name('expressquery')->where('id',$expressquery_id)->find();
        $list = $expModle->getExpressList($expressquery_info['express'], $expresssn, $phone);
        return $list;
}

    //订单列表
    public function orderList()
    {
        $user = $this->auth->getUserinfo();
        $order_status=$this->request->param('order_status');
        $where=[];
        $where['o.user_id']=$user['id'];
        if($order_status){
            $where['order_status'] = $order_status;
        }else{
            $where['order_status'] = array('in',[1,2,5,6]);
        }
        $list = Db::name('order')->alias('o')
            ->join('goods g', 'o.goods_id = g.goods_id')
            ->join('user_address a', 'o.address_id = a.address_id')
            ->where($where)
            ->field('o.*,g.name,g.price,g.stock,g.sales,g.goods_image,g.description,a.recipient_name,a.phone_number,a.address_line,a.area,a.city,a.province')
            ->paginate()->each(function ($item) {
                $item['goods_image'] = cdnurl($item['goods_image'], true);
                $item['createtime'] = date("Y-m-d H:i:s", $item['createtime']);
                $item['updatetime'] = date("Y-m-d H:i:s", $item['updatetime']);
                return $item;
            });
        $this->success(__('Operation completed'), $list);
    }

    //订单支付
    public function orderPay()
    {
        $user = $this->auth->getUserinfo();
        $order_id = $this->request->param('order_id');
        if (!$order_id) {
            $this->error(__('Invalid parameters'));
        }
        $order_info = Db::name('order')->where('order_id', $order_id)->find();
        if (!$order_info) {
            $this->error(__('No results were found'));
        }
        if ($order_info['order_status'] > 1) {
            $this->error(__('Invalid order'));
        }
        $pay = new Pay();
        Db::startTrans();
        try {
            if ($order_info['pay_type'] == 1) {
                $res = $pay->pay($order_info['order_sn'], $order_info['total_amount'], $user['id']);
            } else {
                $user_info = Db::name('user')->where('id', $user['id'])->find();
                $sx_score = bcdiv($order_info['total_amount'], 2, 2);
                if ($user_info['score'] < $sx_score) {
                    $this->error(__('Insufficient balance'));
                } else {
                    Db::name('user')->where('id', $user['id'])->setDec('score', $sx_score);
                    add_score_log($user['id'], -$sx_score, $user_info['score'], bcadd($user_info['score'], $sx_score, 2), '购物', 2);
                    $res = $pay->pay($order_info['order_sn'], $sx_score, $user['id']);
                }
            }
            if ($res['code'] == 200) {
                Db::commit();
                $this->success(__('Operation completed'), $res['data']);
            } else {
                throw new Exception($res['info']);
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    //取消订单
    public function cancelOrder(){
        $user = $this->auth->getUserinfo();
        $order_id = $this->request->param('order_id');
        $order_info=Db::name('order')->where('order_id',$order_id)->find();
        Db::startTrans();
        try {
            $id=Db::name('order')->where('order_id',$order_id)->update(['order_status'=>3]);
            if($id){
                $rs=Db::name('goods')->where('goods_id',$order_info['goods_id'])->setInc('stock',1);
                if(!$rs){
                    throw new Exception("Operation failed");
                }
            }else{
                throw new Exception("Operation failed");
            }
            Db::commit();
            $this->success(__('Operation completed'));
        }catch (Exception $e){
           Db::rollback();
            $this->error($e->getMessage());
        }
    }
    //确认收货
    public function confirmReceipt(){
        $user = $this->auth->getUserinfo();
        $order_id = $this->request->param('order_id');
        $order_info=Db::name('order')->where('order_id',$order_id)->find();
        $data=[];
        $data['order_status']=6;
        $data['updatetime']=time();
        $rs=Db::name('order')->where('order_id',$order_id)->update($data);
        if($rs){
            $this->success(__('Operation completed'));
        }else{
            $this->error(__('Operation failed'));
        }
    }
}